<?php

namespace app\index\controller;
use think\Session;
use think\captcha\Captcha;
use Think\Controller;
use think\Request;

class Login  extends \think\Controller {

	public function login() {
		//如果已经登录，则直接跳到首页
		if (Session::has('username')) {
			return redirect('../index');
		}

		return $this -> fetch();

	}

	public function toLogin() {
		if (Request::instance() -> isPost()) {
			$username = $_POST['username'];
			$password = $_POST['password'];
			$verificationCode = $_POST['verificationCode'];
			//验证码
			if (!captcha_check($verificationCode)) {
				return "验证码不正确";
			} else {
				$rs = \think\Db::table('bk_admin') -> where('username', $username) -> find();
				if ($rs['password'] == $password) {
					//生成session_id随机数
					$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
					$len = strlen($str) - 1;
					$randstr = '';
					for ($i = 0; $i < 16; $i++) {
						$num = mt_rand(0, 16);
						$randstr .= $str[$num];
					}
					$data = ['session_id'=>$randstr];
					\think\Db::table('bk_admin') -> where('username', $username) -> update($data);
					
					//session_id存入session
					Session::set('session_id', $randstr);
					Session::set('username', $username);
					return 0;
					
				} else {
					return 1;
				}
			}

		}
	}

	public function verify() {
		$captcha = new Captcha();
		$captcha -> fontttf = '5.ttf';
		$captcha -> codeSet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$captcha -> fontSize = 140;
		$captcha -> length = 4;
		$captcha -> useNoise = true;

		return $captcha -> entry();
	}

}
